package com.xs.ahoi.hcxs.utils;


import de.innosystec.unrar.Archive;
import de.innosystec.unrar.NativeStorage;
import de.innosystec.unrar.rarfile.FileHeader;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

/**
 * 解压工具类
 */
public class ZipUtils {

    private static boolean unZip4j(String zipFilePath, String outPath, String fileName) {
        try {

            File zipFile = new File(zipFilePath);

            ZipFile zip = new ZipFile(zipFile, "GBK");
            Enumeration entries = zip.getEntries();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry entry;
                try {
                    entry = (ZipArchiveEntry) entries.nextElement();
                } catch (Exception e) {
                    return false;
                }

                String entryName = entry.getName();
                if (entryName.equals("all.txt")) {
                    entryName = fileName.replace(".zip", ".txt");
                }
                InputStream in = zip.getInputStream(entry);
                outPath += entryName;

                File file = new File(outPath);
                if (file.isDirectory()) {
                    file.mkdirs();
                } else if (!file.exists()) {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }

                OutputStream out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[2048];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
                in.close();
                out.close();
            }
            zip.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 解压rar格式压缩包。
     * 对应的是java-unrar-0.3.jar，但是java-unrar-0.3.jar又会用到commons-logging-1.1.1.jar
     */
    private static boolean unrar(String sourceRar, String outPath) {
        Archive a = null;
        FileOutputStream fos = null;
        try {
            NativeStorage nativeStorage = new NativeStorage(new File(sourceRar));
            a = new Archive(nativeStorage);
            FileHeader fh = a.nextFileHeader();
            while (fh != null) {
                if (!fh.isDirectory()) {
                    //1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
                    String compressFileName = fh.getFileNameW().trim();
                    String destFileName = "";
                    String destDirName = "";
                    //非windows系统
                    if (File.separator.equals("/")) {
                        destFileName = outPath + compressFileName.replaceAll("\\\\", "/");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
                        //windows系统
                    } else {
                        destFileName = outPath + compressFileName.replaceAll("/", "\\\\");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
                    }
                    //2创建文件夹
                    File dir = new File(destDirName);
                    if (!dir.exists() || !dir.isDirectory()) {
                        dir.mkdirs();
                    }
                    //3解压缩文件
                    fos = new FileOutputStream(new File(destFileName));
                    a.extractFile(fh, fos);
                    fos.close();
                    fos = null;
                }
                fh = a.nextFileHeader();
            }
            a.close();
            a = null;
        } catch (Exception e) {
            return false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (a != null) {
                try {
                    a.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * 解压缩
     */
    public static Boolean unCompress(String sourceFile) {
        String outPath = sourceFile.substring(0, sourceFile.lastIndexOf("/") + 1);
        String fileName = sourceFile.substring(sourceFile.lastIndexOf("/") + 1);

        //保证文件夹路径最后是"/"或者"\"
        char lastChar = outPath.charAt(outPath.length() - 1);
        if (lastChar != '/' && lastChar != '\\') {
            outPath += File.separator;
        }

        Boolean result = null;
        //根据类型，进行相应的解压缩
        String type = sourceFile.substring(sourceFile.lastIndexOf(".") + 1);
        if (type.equals("zip")) {
            result = unZip4j(sourceFile, outPath, fileName);
        } else if (type.equals("rar")) {
            result = unrar(sourceFile, outPath);
        }


        return result;
    }
}